/**
 * 
 */
package kulstats.server;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kulstats.ActivityController;
import kulstats.CalculatePoints;
import kulstats.MilestoneController;
import kulstats.Question;
import kulstats.Registry;
import kulstats.User;
import kulstats.UserManager;

import org.json.simple.JSONObject;



/**
 * @author steven
 *
 */
public class TrackServlet extends HttpServlet {
    @Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
              throws IOException {
    	//resp.sendRedirect("/track");
    	doPost(req,resp);
    }
    
    @SuppressWarnings("unchecked")
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	    	throws IOException {
    	
    	User currentUser = Registry.userManager().getCurrentUser();
    	if(currentUser == null) {
    		resp.sendRedirect("/login");
    		return;
    	}
    	
    	JSONObject answer = new JSONObject();
    	
    	String doAction = req.getParameter("action");
    	ActivityController activityController = ActivityController.getInstance();
    	
    	System.out.println("DoTrack: " + doAction);
    	
    	if(doAction.equals("action_new")) {
	    	String trackType        = req.getParameter("track_type"); //= study / class / other
	    	long trackStart         = Long.parseLong(req.getParameter("track_start")); //javascript Date object .toUTCString() string
	    	String trackCourse      = req.getParameter("track_course"); //CourseID
	    	String trackLessonType  = req.getParameter("track_lesson_type"); //LessonType
	    	String trackLocation    = req.getParameter("track_location"); //LocationID
	    	String trackSpareType   = req.getParameter("track_spare_type"); // SpareTimeType
	    	 
	    	if(activityController.startActivity(trackType, trackStart, trackCourse, trackLessonType, trackLocation, trackSpareType)) {
    			answer.put("status", "success");
    	    	MilestoneController milestoneController = MilestoneController.getInstance();
    			LinkedList<Long> progressVals = milestoneController.getProgressWhileTracking(trackCourse);
    			answer.put("progress_now", progressVals.get(0));
    			answer.put("progress_tot", progressVals.get(1));
    		}
    		else {
    			answer.put("status", "failed");
    		}
    	}
    	if(doAction.equals("action_stop")) {
    		Date stop = new Date(Long.parseLong(req.getParameter("track_stop")));
    		CalculatePoints cp = new CalculatePoints();
    		if(activityController.stopActivity(stop)) {
    			answer.put("status", "success");
    			cp.updatePoints();
    			doAction = "action_get_questions";
    		}
    		else {
    			answer.put("status", "failed");
    		}
    	}
    	if(doAction.equals("action_start_pause")) {
    		Date pause = new Date(Long.parseLong(req.getParameter("pause_start")));
    		if(activityController.startPause(pause)) {
    			answer.put("status", "success");
    		}
    		else {
    			answer.put("status", "failed");
    		}
    	}
    	if(doAction.equals("action_stop_pause")) {
    		Date pause = new Date(Long.parseLong(req.getParameter("pause_stop")));
    		if(activityController.stopPause(pause)) {
    			answer.put("status", "success");
    		}
    		else {
    			answer.put("status", "failed");
    		}
    	}
    	if(doAction.equals("action_get_questions")) {
    		LinkedHashMap<Question,List<String>> questions = activityController.getQuestions();
    		if(!questions.isEmpty()) {
    			LinkedList jsonQuestions = new LinkedList();
    			for(Question q : questions.keySet()) {
    				JSONObject jsonQ = new JSONObject();
    				jsonQ.put("qid", q.getQuestionID());
    				jsonQ.put("question", q.getQuestion());
    				jsonQ.put("alistid", q.getAnswerlist());
    				jsonQ.put("alist", questions.get(q));
    				jsonQuestions.add(jsonQ);
    			}
    			answer.put("questions", jsonQuestions);
    		}
    		else {
    			//answer.put("status", "failed");
    		}
    	}
    	if(doAction.equals("action_save_questions")) {
    		Map<Integer, String> answers = new HashMap<Integer, String>();
    		for(int i=0  ; req.getParameter("track_question_"+i) != null && req.getParameter("track_question_"+i+"_qid") != null ; i++) {
    			answers.put(Integer.parseInt(req.getParameter("track_question_"+i+"_qid")), req.getParameter("track_question_"+i));
    		}
    		if(activityController.saveQuestions(answers)) {
    			answer.put("status", "success");
    		}
    		else {
    			answer.put("status", "failed");
    		}
    	}
    	/*if(doAction.equals("action_skip_questions")) {
    		if(activityController.skipQuestions()) {
    			answer.put("status", "success");
    		}
    		else {
    			answer.put("status", "failed");
    		}
    	}*/

    	resp.setContentType("text/plain");
    	resp.getWriter().println(answer);
    }
}
